<?php namespace Hdphp\Route;

class Route extends Parse
{
	//路由定义
	protected $routes=array();

	//找到路由
	protected $found=false;

	//请求的URI
	protected $uri;

	//路由前缀(用于路由组)
	protected $prefix;	

	//正则替换字符
	protected $patterns=array(
		':num'=>'[0-9]+',
		':all'=>'.*'
		);

	public function __construct()
	{
		$this->getRequestUri();

		$this->setConst();
	}

	//请求地址
	protected function getRequestUri()
	{
		$this->uri = $_SERVER['REQUEST_URI'];
	}

	//定义HTTP常量
	protected function setConst()
	{
		define('IS_GET',     	$_SERVER['REQUEST_METHOD'] == 'GET' );
		define('IS_POST',    	$_SERVER['REQUEST_METHOD'] == 'POST');
		define('IS_DELETE',    	$_SERVER['REQUEST_METHOD'] == 'DELETE');
		define('IS_PUT',  		$_SERVER['REQUEST_METHOD'] == 'PUT'?true:(Q('post._method')=='PUT'));
		define('IS_AJAX',    	isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
								&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
		define('__ROOT__',		trim('http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']),'/'));
		define("__HISTORY__", 	isset($_SERVER["HTTP_REFERER"])?$_SERVER["HTTP_REFERER"]:null);
	}

	/**
	 * 魔术方法用于设置路由
	 * get/post/put/delete/any
	 * @param  	string $method 	请求动作
	 * @param  	array 	$params 参数数组
	 * @return 	object
	 */
	public function __call($method,$params)
	{
		$route['method']=$this->prefix.$method;
		$route['route']=array_shift($params);
		$route['callback']=array_shift($params);
		$route['regexp']='/./';//经过计算后的url 正则验证规则
		$route['args']=array();//解析后的请求参数
		$this->routes[] = $route;
		p($this->routes);
		return $this;
	}

	/**
	 * 路由组
	 * @param  array  	$prefix   路由前缀
	 * @param  Closure 	$callback 回调函数
	 * @return void;
	 */
	public function group(array $prefix,$callback)
	{
		$this->prefix = $prefix['prefix'].'/';
		$callback();
		$this->prefix = '';
		return $this;
	}

	/**
	 * 设置控制器路由
	 * @param  [type] $route [description]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function controller($route,$param)
	{
		$this->route[]=array(
			'method'=>'controller',
			'route'=>trim($this->prefix.$route,'/').'/{method}',
			'callback'=>$param,
			'regexp'=>'',
			'args'=>array()
			);
		return $this;
	}

	/**
	 * 设置资源路由
	 * @param  [type] $route [description]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function resource($route,$controller)
	{
		$this->get("$route",$controller.'@index');
		//添加文章视图
		$this->get("$route/create",$controller.'@create');
		//保存
		$this->post("$route",$controller.'@store');
		//显示文章
		$this->get("$route/{id}",$controller.'@show');
		//编辑文章视图
		$this->get("$route/{id}/edit",$controller.'@edit');
		//更新
		$this->put("$route/{id}",$controller.'@update');
		//删除文章
		$this->delete("$route/{id}",$controller.'@destroy');

		return $this;
	}

	/**
	 * 参数验证
	 * @param  string $name   变量名
	 * @param  regexp $regexp 正则验证规则
	 * @return void
	 */
	public function where($name,$regexp=null)
	{
		if(is_array($name))
		{
			foreach($name as $k=>$v)
			{
				$this->routes[count($this->route)-1]['where'][$k]='#^'.$v.'$#';
			}
		}
		else
		{
			$this->routes[count($this->route)-1]['where'][$name]='#^'.$regexp.'$#';
		}	
	}

	/**
	 * 验证路由参数
	 * @param  int 	$id  顺序号
	 * @return bool
	 */
	protected function checkArgs($id)
	{
		$route= $this->route[$id];
		if(!empty($route['where']))
		{
			foreach($route['where'] as $name=>$regexp)
			{
				if(isset($route['get'][$name]) && !preg_match($regexp,$route['get'][$name]))
				{
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 运行路由处理
	 * @return [type] [description]
	 */
	public function make()
	{
		foreach((array)$this->routes as $id=>$route)
		{
			if(method_exists($this,$route['action']))
			{
				$this->$route['action']($id,$route['url'],$route['callback']);
			}
		}
	}
}